// pages/mine/address/edit_address/edit_address.ts
import { addAddress, detailAddress, updateAddress } from '../../../api/custom'
import { toast } from '@/utils/extendApi'
import QQMapWX from '../../../lib/qqmap-wx-jssdk'
import Schema from 'async-validator'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    id: {
      type: String
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    addressData: {
      id: "",
      name: "", //名称
      mobile: "", //电话
      provincialCode: '',
      provincialName: "",//省名称
      cityCode: '',
      cityName: "",//市名称
      areaCode: '',
      areaName: "",//区名称
      detail: "",
      defaulted: false
    }
  },
  lifetimes: {
    attached() {
      if(this.properties.id){
        this.getDetail(this.properties.id)
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onAddressChange(event: any) {
      const [provincialName, cityName, areasName] = event.detail.value
      const [provincialCode, cityCode, areasCode] = event.detail.code
      this.setData({
        'addressData.provincialName': provincialName,
        'addressData.cityName': cityName,
        'addressData.areaName': areasName,
        'addressData.provincialCode': provincialCode,
        'addressData.cityCode': cityCode,
        'addressData.areaCode': areasCode
      })
    },
    getDetail(id: string) {
      detailAddress(id).then(res => {
        this.setData({
          addressData: res.data
        })
      })

    },
    async submit(e: any) {
      
      e.detail.value.defaulted = e.detail.value.defaulted ? 1 : 0
      const data = Object.assign({}, this.data.addressData, e.detail.value)
      const { valid } = await this.validatorAddress(e.detail.value)
      if (!valid)  return
      if (data.id) {
        updateAddress(data).then(res => {
          toast({ title: '更新成功', icon: 'success' })
          wx.navigateBack()
        })
      } else {
        addAddress(data).then(res => {
          toast({ title: '添加成功', icon: 'success' })
          wx.navigateBack()
        })
      }
    },
    async chooseAddress() {
      try {
        const { latitude, longitude, name } = await wx.chooseLocation()
        const qMap = new QQMapWX({ key: 'GMUBZ-ELUWW-QS4RQ-Y3ZZ3-ZFEOK-QIFCK' })
        qMap.reverseGeocoder({
          location: {
            longitude,
            latitude
          },
          success: (res: any) => {
            console.log(res)
            const { city, district, province, adcode } = res.result.ad_info
            const { street, street_number } = res.result.address_component
            this.setData({
              'addressData.provincialName': province,
              'addressData.cityName': city,
              'addressData.areaName': district,
              'addressData.provincialCode': adcode.replace(adcode.substring(2, 6), '0000'),
              'addressData.cityCode': adcode.replace(adcode.substring(4, 6), '00'),
              'addressData.areaCode': district && adcode,
              'addressData.detail': street + street_number + name
            })
          }
        })

      } catch (error) {
        toast({ title: "获取地址失败" })
      }
    },
    validatorAddress(param: any) {
      // 验证收货人，是否只包含大小写字母、数字和中文字符
      const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
      // 验证手机号，是否符合中国大陆手机号码的格式
      const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
      const rules = {
        name: [
          { required: true, message: '请输入收货人名称' },
          { pattern: nameRegExp, message: "收货人姓名不合法" }
        ],
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: phoneReg, message: "手机号不合法" }
        ],
        provincialName: { required: true, message: '请输入收货人所在地区' },
        detail: { required: true, message: '请输入收货人详细地址' },
      }
      const validator = new Schema(rules)
      return new Promise((resolve) => {
        validator.validate(param, (errors: any) => {
          if (errors) {
            toast({ title: errors[0].message })
            resolve({ valid: false })
          } else {
            resolve({ valid: true })
          }
        })
      })
    }
  }

})